//设备台账
import React, { Component } from 'react';
import { Table, Button, Form, Card, Tabs, message ,Menu, Dropdown} from 'antd';
import '@/assets/css/settings';
import BasicForm from '../../components_yyr/common/basicForm';
import { withRouter } from 'react-router-dom';
import BasicDrawers from "../../components_yyr/common/basicDrawers";
import { FileDown, FileUpload } from '../../components_yyr/commponent/File';
import Paging from '../../components_yyr/commponent/Paging';
import BasicConfirm from '../../components_yyr/common/basicConfirm';
import QRCode from 'qrcode.react'
// import { util } from 'webpack';
import Zmage from 'react-zmage'
import * as Utils from '../../utils_yyr/action';
import { euqApplicationName, lotAuth, lotAuth2 } from '../../config';
const { TabPane } = Tabs;

const nowDate = Utils.getNowDate()
const mainFactoryList = {
	//设备类别
	equTypeId: [/* { value: '维护分布', title: '维护分布', },
	{ value: '头孢固体一车间 ', title: '头孢固体一车间 ' },
	{ value: '资源管理部 ', title: '资源管理部 ', children: [{ value: '维护分布', title: '维护分布' },] } */
	
	],
	
	// 使用状况
	usezk: [{ id: 1, value: '在用' }, { id: 2, value: '维修' }],
	//使用部门
	doorMinimumPrice: [
		{ value: '维护分布', title: '维护分布', },
		{ value: '头孢固体一车间 ', title: '头孢固体一车间 ' },
		{ value: '资源管理部 ', title: '资源管理部 ', children: [{ value: '维护分布', title: '维护分布' },] }],
	// 维修组
	repairTeamId: [{ id: 1, value: '维修班组' }, { id: 2, value: '系统评估班组' }],
};

class EquipmentList extends Component {
	state = {
		loading: false, //加载中...
		dataSource: [], //数据源
		drawerVisible: false, //新增修改抽屉的显示与隐藏
		chooseData: {},
		drawerTitle: '',
		total: 0,
		formValues: {},
		cityData: [],
		mainFactoryList: [],
		selectedData: [],
		selectedKeys: [],
		data:[],
		syzk:[],
		handleType:0,
		DepartmentList:[],
		zydw:[],
		wldw:[],
		wxz:[],
		printBatchList:[],
		pId:{},
		dataSource1:[],
		dataSource2:[],
		dataSource3:[],
		dataSource4:[],
		dataSource5:[],
		loading_cz:false
	};

	componentDidMount() {
		this.fetch({
			pageNum: 1,
			pageSize: 10
		});
	    this.queryTreeDepartment()
		this.findEquTypePageList()
		this.syzk()
		this.zydw()
		this.wldw()
		this.wxz()
	}
	//数据加载获取数据库data
	fetch = data => {
		console.log(data)
		let str = ''
		for(var key in data){
			if(data[key]){
				str += `&${key}=${data[key]}`
			}
		}
		this.setState({ loading: true })
		this.get(euqApplicationName + '/equipmentInfo/findEquInfoList?'+str).then(res => {
			let dataSource = res.data.data
			dataSource = this.getList(dataSource)
			let data2=[]
			for (const iterator of dataSource) {
				if(iterator.isChildren!==0)
				iterator.children=[]
				data2.push(iterator)
			}
			this.setState({
				loading: false,
				total:res.data.total,
				formValues:data,
				selectedRows:[],
				selectedKeys:[],
				dataSource:data2
		 	});
		 })
	};
	getList = (data) =>{
		data && data.map(item => {
			if (item.children&&item.children.length>0) {
				return (this.getList(item.children));
			}
			delete item.children;
		})
		return data
	};
	queryTreeDepartment = () => {
		// this.get(lotAuth + '/department/queryTreeDepartment').then(res => {
		this.get(lotAuth2 + '/department/queryTreeDepartment').then(res => {
			this.setState({
				DepartmentList: res.data
			});
		})
	}
	syzk = () => {
		 this.setState({ loading: true })
		this.get(euqApplicationName + '/api/findEquipmentNextParameterPageList?typeId=2').then(res => {
		this.setState({
			syzk: res.data,
		 	});
		})
	}; 

	findEquTypePageList = () => {
		this.setState({ loading: true })
		this.get(euqApplicationName + '/parameter_setting_equipmentType/findEquTypePageList').then(res => {
		this.setState({
	   		data: res.data,
			});
		})
   }; 

   zydw = () => {//租用单位列表
	   this.get(euqApplicationName + '/parameter_setting_public/queryRentDepartmentByParam?type=2&pageNum=1&pageSize=99999').then(res => {
		this.setState({
			zydw: res.data,
		});
	})
   }

   wldw = () => {//往来单位列表
	   this.get(euqApplicationName + '/parameter_setting_public/queryRentDepartmentByParam?type=1&pageNum=1&pageSize=99999').then(res => {
		this.setState({
			wldw: res.data,
		});
	})
   }	
   	wxz = () => {//维修组
		this.get(euqApplicationName + '/parameter_setting_public/queryTeamPageList?type=维修').then(res => {
		this.setState({
			wxz: res.data,
		});
		})
	}; 
	getInfo = () => {
	this.get(euqApplicationName + '/equipmentInfo/findEquInfoList').then(res => this.setState({ mainFactoryList: res.data.data })); //主机厂
	};

	//表单查询
	filterSubmit = values => {
		console.log("表单查询=====", values)
		values.pageNum = this.state.formValues.pageNum;
		values.pageSize = this.state.formValues.pageSize;
		this.fetch(values);
	};

	// 表格删除
	handleConfirm = (value, api, chooseData) => {
		console.log(this.state.selectedData)
		let str = ''
		for(var item of this.state.selectedData){
			str += item.id + ','
		}
		this.delete(`${euqApplicationName}/equipmentInfo/deleteEquInfo?ids=${str.slice(0, str.length - 1)}`).then(res => {
			this.success();
			this.fetch({ ...this.state.formValues });
			this.setState({selectedKeys:[]})
		});
   };

	// 表格打印
	handlePrinting = (data, type) => {
        const that = this;
        //单次打印
        if (data.length === 0) {
            // Utils.openNotification('warning', '请先选择设备！')
			this.get(euqApplicationName + '/equipmentInfo/findEquInfoList?pageSize=99999&pageNum=1').then(res => {
				let data = res.data.data
				new Promise(function(resolve){
					that.setState({ printBatchList : data});
					setTimeout(function(){
						resolve(data);
					},100)
					}).then(data=>{
					for (var i = 0; i < data.length; i++) {
						that.changeImg(i)
					}
				}).then(() => {
					var printInnerHTML = window.document.getElementById('billDetails_ln').innerHTML;
					window.document.body.innerHTML = printInnerHTML
					window.print();
					window.location.reload();
				})
			})
        }else{
			new Promise(function(resolve){
				that.setState({ printBatchList : data});
				setTimeout(function(){
					resolve(data);
				},100)
				}).then(data=>{
                for (var i = 0; i < data.length; i++) {
                    that.changeImg(i)
                }
            }).then(() => {
                var printInnerHTML = window.document.getElementById('billDetails_ln').innerHTML;
                window.document.body.innerHTML = printInnerHTML
                window.print();
                window.location.reload();
            })
	}
		} 
		
		canvasToImage = (canvas) => {
			var image = new Image();
			// 指定格式 PNG 图片后缀可自定义
			image.src = canvas.toDataURL("image/png");
			image.style = "height:100%";
			return image;
		}
		changeImg = (i) => {
			var mycanvas = document.getElementsByTagName('canvas');
			// console.log(mycanvas[i])
			var img = this.canvasToImage(mycanvas[i]);
			var ewmImg = document.getElementById('ewm' + i);
			ewmImg.append(img);
			// console.log(ewmImg)
		}
	
	formList = () => {
		const {  DepartmentList } = this.state;
		const formList = [
			// {
			// 	type: 'SELECT', label: '使用部门', field: 'depId', name: 'value',
			// 	list: [{ id: 1, value: '维护分布' }, { id: 2, value: '头孢固体一车间' }],
			// 	valueField: 'value'
			// },
			{ type: "TREESELECT", label: "使用部门", field: "depId", name: 'name', valueField: 'id', list: DepartmentList ,allowClear:true},
			{
				type: 'TREESELECT', label: '设备类别', field: 'equTypeId', 
				name: 'name', valueField: 'id', list:this.state.data,allowClear:true
			},
			// { type: 'TREESELECT', label: '设备类别', field: 'equType',  name: 'name', valueField: 'id', list:EquTypePageList,allowClear:true},
			// { type: 'INPUT', label: '设备编号', field: 'equCode' },
			{ type: 'INPUT', label: '快速查询', field: 'quickSearch',placeholder:'设备名称和编号' },
		];
		return formList;  
	};
	drawerFormList = data => {
		const { mainFactoryList ,syzk ,DepartmentList,zydw,wldw,wxz } = this.state;
		const drawerFormList = [
			{ type: 'TITLE', label: '基本信息' },
			{ type: 'INPUT', label: '设备编号', field: 'equCode', initialValue: data.equCode,placeholder:'自动生成' },
			{ type: 'INPUT', label: '设备名称', field: 'equName', initialValue: data.equName, required: true },
			{ type: 'TREESELECT', label: '设备类别', field: 'equTypeId', initialValue: data.equTypeId, name: 'name', valueField: 'id', list:this.state.data,allowClear:true},
			{ type: 'INPUT', label: '规格型号', field: 'equSpecsModel', initialValue: data.equSpecsModel },
			{ type: 'SELECT', label: '生产厂商', field: 'equManufacturerId', initialValue: data.equManufacturerId ,treeCheckable:false, name: 'name', valueField: 'id', list: zydw.concat(wldw)},
			{ type: 'SELECT', label: '供应商', field: 'equSupplierId', initialValue: data.equSupplierId ,treeCheckable:false, name: 'name', valueField: 'id', list: wldw},
			{ type: 'INPUT', label: '使用寿命', field: 'equUsefulLife', initialValue: data.equUsefulLife },
			{ type: 'DATE', label: '购买时间', field: 'dateSec_purchaseTime', initialValue: data.purchaseTime ? data.purchaseTime : nowDate },
			{ type: 'INPUT', label: '资产原值', field: 'equNetWorth', initialValue: data.equNetWorth },
			{ type: 'INPUT', label: '资产净值', field: 'equNetAsset', initialValue: data.equNetAsset },
			{ type: 'INPUT', label: '资产负责人', field: 'equAssetPersonName', initialValue: data.equAssetPersonName },
			{ type: 'DATE', label: '验收时间', field: 'dateSec_requiredAcceptanceTime', initialValue: data.requiredAcceptanceTime ? data.requiredAcceptanceTime : nowDate},
			{ type: 'SELECT', label: '设备标记', field: 'equSign', initialValue: data.equSign, name: 'name', valueField: 'id',
				list: [{ id: '1', name: '重点设备'},{ id: '2', name: '主要设备' },{ id: '3', name: '一般设备' },{ id: '4', name: '其他'},],
			},
			{ type: 'TITLE', label: '使用状况' },
			{ type: 'SELECT', label: '使用状况', field: 'useStatus', initialValue: data.useStatus, name: 'configValue', valueField: 'id', list:   syzk},
			{ type: 'TREESELECT', label: '使用部门', field: 'depId', initialValue: data.depId, name: 'name', valueField: 'id', list: DepartmentList},
			{ type: 'INPUT', label: '操作人', field: 'operate', initialValue: data.operate},
			{ type: 'SELECT', label: '维修组', field: 'repairTeamId', initialValue: data.repairTeamId, name: 'name', valueField: 'id', list: wxz},
			{ type: 'SELECT', label: '租用单位', field: 'hireId', initialValue: data.hireId , name: 'name', valueField: 'id', list: zydw},
			{ type: 'INPUT', label: '使用位置', field: 'equipmentLocation', initialValue: data.equipmentLocation },
		];
		let obj = { type: "FILEUPLOAD", label: "图片上传", field: "upload_pictureId" ,apiPath:'/lot-file/file/uploadFile' ,buttonName:'上传图片' , fileId :true,parameter:{userId:localStorage.getItem('userId')}}
		if(this.state.handleType === 0){
			drawerFormList.push(obj)
		}
		return drawerFormList;
	};

	// 提交modal
	handleSubmit = data => {
		const { dataSource, chooseData ,handleType} = this.state;
		//数据新增提交保存
		 const id = this.state.chooseData && this.state.chooseData.id;
		 if (handleType===1) {
		 	data.id = chooseData.id
		 	data.updateId = localStorage.getItem('userId');
			 data.sid = this.state.chooseData.sid
		 } else {
		 	data.createId = localStorage.getItem('userId');
		 }
		 console.log(data)
		 this.post(euqApplicationName + '/equipmentInfo/saveEquipmentInfo',{data}).then(res => {
		 	this.success();
		 	this.fetch({ ...this.state.formValues });
		 	this.onClose();
		 });
	};

	// 打开modal，判断是修改还是新增 0新增 1修改
	handleModal = (type, data) => {
		if (type===1) {
			this.setState({
				drawerTitle: '详情',
				drawerVisible: true,
				chooseData: data,
				handleType : type
			});
		} else{
			this.setState({
				drawerTitle: '新增',
				drawerVisible: true,
				handleType : type,
				chooseData: data,
			});
		}
	};


	onClose = () => {
		this.setState({
			drawerVisible: false,
			chooseData: {}
		});
		 this.modalRef.props.form.resetFields();
	};

	onRowClick = (record) => {
		console.log(record)
		this.setState({loading_cz:true})
		if(record.imgPath && record.imgPath.length>0){
			this.setState({pictureIdList:record.imgPath,pictureIds:record.pictureIdList})
		}else{
			this.setState({pictureIdList:[],pictureIds:[]})
		}
		this.setState({selectedKeys:[record.id],ChoosePicList:[],chooseData:record})
		this.get(euqApplicationName + '/equipmentRepairFault/findEquipmentRepairFaultList?').then(res => {
			this.setState({
				loading_cz: false,
				dataSource1: res.data.data,
			});
		})
		// this.get(euqApplicationName + `/equipmentRepairFault/findEquipmentRepairFaultOperationRecordList?id=${record.iid}`).then(res=>{
		// 	this.setState({FaultOperationRecordList:res.data,loading_cz:false})
		// })
	}
	getEquChildren = () => {
		let {selectedKeys,selectedData} = this.state
		if(selectedKeys.length!==1){
			Utils.openNotification('warning','请勾选一行附加子设备!')
			return
		}
		// let obj = {equName:selectedData[0].equName,equCode:selectedData[0].equCode}
		this.props.history.push('/AddEquipmentChildren/'+selectedKeys[0])
	}
	delEquChildren = () => {
		let {selectedKeys,selectedData} = this.state
		if(selectedKeys.length===0){
			Utils.openNotification('warning','请至少勾选一行移除!')
			return
		}
		let str = ''
		for(var item of selectedData){
			str += item.id + ','
		}
		this.get(euqApplicationName + '/equipmentInfo/delSubset?ids='+str.slice(0, str.length - 1)).then(res => {
			this.success();
			this.fetch({...this.state.formValues})
		});
	}
	onExpand=(expanded, record)=>{
		if(expanded){
			console.log(record)
			this.get(euqApplicationName + '/equipmentInfo/findAllSubset?id='+record.id).then(res => {
				let dataSource=this.state.dataSource,data=res.data
				for (let i=0;i<dataSource.length;i++) {
					if(dataSource[i].id===record.id){
						for (const key2 in data) {
							if(data[key2].isChildren!==0){
								res.data[key2].children=[]
							}else{
								if(res.data[key2].children)
								delete res.data[key2].children
							}
						}
						dataSource[i].children=data
						break
					}
				}
				this.setState({dataSource})
			});
		}
	}
	render() {
		//文件上传
		const props = {
			name: 'file',
			action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
			headers: {
				authorization: 'authorization-text'
			},
			onChange(info) {
				if (info.file.status !== 'uploading') {
					console.log(info.file, info.fileList);
				}
				if (info.file.status === 'done') {
					message.success(`${info.file.name} file uploaded successfully`);
				} else if (info.file.status === 'error') {
					message.error(`${info.file.name} file upload failed.`);
				}
			}
		};
//数据删除
		const columns = [
			{
				title: '详细', width: 70, dataIndex: 'operation',fixed:'left',
				render: (text, record) => {
				return <span><a href onClick={() => this.handleModal(1, record)}>详细</a></span>
				}
			},
			{ title: '设备图片', width: 180, dataIndex: 'tomcatPath' ,fixed:'left',render:(text)=>{
				return text ? <Zmage src={text} style={{width:150,height:120,}}/> : ''
			}},
			{ title: '设备名称', width: 180, dataIndex: 'equName',fixed:'left',},
			{ title: '设备编码', width: 150, dataIndex: 'equCode',fixed:'left', },
			{ title: '规格型号', width: 100, dataIndex: 'equSpecsModel',fixed:'left', },
			{ title: '设备类型', width: 150, dataIndex: 'equTypeName' ,fixed:'left',},
			{ title: '部门名称', width: 150, dataIndex: 'userDepartmentName' },
			{ title: '操作人'  , width: 100, dataIndex: 'operate' },
			{ title: '生产厂商', width: 150, dataIndex: 'equManufacturerName' },
			{ title: '供应商'  , width: 150, dataIndex: 'equSupplierName' },
			{ title: '设备位置', width: 200, dataIndex: 'equipmentLocation' },
			{ title: '使用状况', width: 150, dataIndex: 'useStatusValue' },
			{ title: '购置时间', width: 200, dataIndex: 'purchaseTime' },
			{ title: '设备标记', width: 150, dataIndex: 'equSign' ,render:(text)=>{
				return text==='1' ? '重点设备' : text==='2' ? '主要设备' : text==='3' ? '一般设备' : text==='4' ? '其他' : ''
			}},
			{ title:'资产负责人', width: 150, dataIndex:'equAssetPersonName' },
			/* { title: '是否在修', width: 150, dataIndex: 'remarks' }, */
		];
		const columns1 = [
			{
				title: '详细', width: 80, 
				render: (text, record) => {
					return <span><a href onClick={() => this.handleModal(1, record)}>详细</a></span>
				}
			},
			{ title: '编号', width: 150, dataIndex: 'orderCode' },
			{ title: '报修状态', width: 100, dataIndex: 'status1' ,render:(text)=>{//
				return text === 1 ? '待审核' : text === 2 ? '审核中' : text === 3 ? '待维修' : text === 4 ? '维修中' : text === 5 ? '待验证' : text === 6 ? '已完成' : ''
			}},
			{ title: '处理状态', width: 100, dataIndex: 'status' ,render:(text)=>{
				return text === 1 ? '待审核' : text === 2 ? '审核中' : text === 3 ? '待维修' : text === 4 ? '维修中' : text === 5 ? '待验证' : text === 6 ? '已完成' : ''
			}},
			{ title: '外委维修', width: 150, dataIndex: 'equName' },//
			{ title: '发生时间', width: 150, dataIndex: 'occurrenceTime' },
			{ title: '创建时间', width: 200, dataIndex: 'occurrenceTime1' },//
			{ title: '维修组', width: 150, dataIndex: 'maintainTeamName' },
			{
				title: '故障等级', width: 150, dataIndex: 'faultLevelName',
			},
			{ title: '故障类别', width: 150, dataIndex: 'faultTypeName' },
			{ title: '故障描述', width: 150, dataIndex: 'faultDescription' }
		];
		const { chooseData, drawerVisible, drawerTitle, dataSource,data, loading, total, formValues, selectedData, selectedKeys } = this.state;
		const drawerProps = {
			onRef: ref => (this.modalRef = ref), visible: drawerVisible, width: 700, drawerFormList: this.drawerFormList(chooseData),
			submit: this.handleSubmit, onClose: this.onClose, title: drawerTitle};

		//选择框
		const rowSelection = {
			selectedRowKeys: selectedKeys,
			onChange: (selectedRowKeys, selectedRows) => {
				this.setState({
					selectedData: selectedRows,
					selectedKeys: selectedRowKeys,
				})
			},
			// getCheckboxProps: record => ({
			// 	disabled: record.name === 'Disabled User',
			// 	name: record.name
			// })
		};
		const menu = (
			<Menu>
			  <Menu.Item>
				<a onClick={()=>{this.getEquChildren()}}>
				  附加子设备
				</a>
			  </Menu.Item>
			  <Menu.Item>
				<a onClick={()=>{this.delEquChildren()}}>
				  移除子设备
				</a>
			  </Menu.Item>
			</Menu>
		  );

		return (
			<div className="shadow-radius">
				<Card>
					<BasicForm formList={this.formList()} filterSubmit={this.filterSubmit} labelSpan={8} wrapperSpan={12} onRef={ref => (this.child = ref)} />
				</Card>

				<Tabs tabBarExtraContent={
				<div className="buttonList">
				<Button icon="plus" onClick={()=>this.handleModal(0,{})} type="primary">{' '}新增</Button>
				<Dropdown overlay={menu} placement="bottomRight">
					<Button icon="diff" type="primary"> 子设备 </Button>
				</Dropdown>
				<BasicConfirm title="确认删除?" api={1} icon="delete" button={true} buttonName="删除" data={selectedData} handleConfirm={()=>this.handleConfirm()} />
						<FileDown fileName="设备台账模板" buttonName="模板下载" apiPath={euqApplicationName + "/equipmentInfo/exportEquipmentInfoListExcelTemplate"}  method="post" />
						<FileDown fileName="设备台账清单" buttonName="导出" method="post" apiPath={euqApplicationName + "/equipmentInfo/exportEquipmentInfoListExcel"} data={{ids:selectedKeys}} />
						<FileUpload buttonName="导入" apiPath={euqApplicationName + "/equipmentInfo/toLeadEquipmentInfoListExcel"} load={true} fetch={() => this.fetch({ ...formValues })} />
				<Button icon="printer" onClick={() => this.handlePrinting(selectedData,0)} type="primary">{' '} 打印</Button>
			    </div>}>

				<TabPane tab="设备台账" key="1">
					<Table columns={columns} rowSelection={rowSelection} rowKey={(record, index) => record.id} dataSource={dataSource} pagination={false} loading={loading} scroll={{ y: 950, x: 1300 }} onRowClick={(record)=>{this.onRowClick(record)}} expandIconColumnIndex={3} 
					onExpand={(expanded,record)=>{this.onExpand(expanded,record)}}/> 
					<Paging total={total} formValues={formValues} fetch={pager => this.fetch(pager)} /> 
				</TabPane>
				</Tabs>

					{/* <Tabs>
				<TabPane tab="故障报修" key="1">
					<Table columns={columns1} rowSelection={rowSelection} rowKey={(record, index) => record.id} dataSource={this.state.dataSource1} pagination={false} loading={this.state.loading_cz} scroll={{ y: 450 ,x:1500}} />
					</TabPane>
					<TabPane tab="维修计划" key="2">
						维修计划
					</TabPane>
					<TabPane tab="保养计划" key="3">
						保养计划
					</TabPane>
				</Tabs> */}

				<BasicDrawers	{...drawerProps} />

				<div id={"billDetails_ln"} style={{ padding: 0, margin: 0,width:'100%'}}>
                <div style={{display:'flex',flexWrap:'wrap', padding: 0,}}>
					{this.state.printBatchList.map((item, i) => {
						console.log(item)
						return <div className='cardStyle' id={'cardStyle' + i} style={{width:'100px',height:'100px',margin:'6px 0 4px 7px',display:'flex',flexWrap:'wrap',color:'black',padding:'10px'}} key={i}>
								{/* // border:'1px black solid' */}
							<div style={{width:'100%'}}>
								<QRCode 
                                value={`${item.id}`}  //value参数为生成二维码的链接
                                size={60} //二维码的宽高尺寸
                                fgColor="#000000"  //二维码的颜色
                                style={{ display: 'none' }} />
                            	<div className="codeImg" id={"ewm" + i} style={{ padding: 0, margin:0,}}></div>
							</div>
							<div style={{width:'80%',margin:'0 auto'}}>
								{item.equName}
							</div>
						</div>
					})}
				</div>

            	</div >
			</div>
		);
	}
}
export default Form.create()(withRouter(EquipmentList));
